package com.sleep.satokendemo.util;

import com.sleep.satokendemo.entry.GroovyContext;
import groovy.lang.GroovyShell;
import groovy.lang.Script;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.util.function.Supplier;

/**
 * @author GuoAo
 * @className GroovyUtil
 * @date 2024/12/18
 * @description TODO
 */
@Component
@RequiredArgsConstructor
public class GroovyUtil {
    private final ResourceLoader resourceLoader;
    public <T> T execute(String fileUrl, String functionName, GroovyContext context, Class<T> type) throws IOException {
        GroovyShell groovyShell = new GroovyShell();
        String filePath = ResourceLoader.CLASSPATH_URL_PREFIX + fileUrl;
        Resource resource = resourceLoader.getResource(filePath);
        File file = resource.getFile();
        Script parse = groovyShell.parse(file);
        Object o = parse.invokeMethod(functionName, context);
        return type.cast(o);


    }

    public <T> T execute(Supplier<String> scriptText, String functionName, GroovyContext context, Class<T> type){
        GroovyShell groovyShell = new GroovyShell();
        Script parse = groovyShell.parse(scriptText.get());
        Object o = parse.invokeMethod(functionName, context);
        return type.cast(o);
    }
}
